// Copyright 2013 Petar Maymounkov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package snowflake

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"path"
	"strconv"
	"strings"
	"sync"
	"time"

	"circuit/kit/docker/docker"
	"circuit/use/n"
)

// Parent loci spin child loci (docker contains) here.
// The child logic is invoked by circuit/cmd/circuit/load.go, and implemented in child.go

// The Snowflake structure manages a circuit's dockerized subordinate circuits.
type Snowflake struct {
	Config       Config
	ParentDir    string // Local directory holding parent circuit's binaries
	ParentBinary string // Name of parent circuit's binary
	//
	sync.Mutex
	buf struct {
		out, err bytes.Buffer
	}
	chamber map[string]*Chamber // Docker container ID –> chamber
}

type Config struct {
	Port      int    // Child port
	Genus     string // Working directory inside child container
	ParentURL string // URL of this parent worker, for purposes of subordinate kinfolk join
}

func NewSnowflake(config Config) (snowflake *Snowflake, err error) {
	snowflake = &Snowflake{
		Config:       config,
		ParentDir:    path.Dir(os.Args[0]),
		ParentBinary: path.Base(os.Args[0]),
	}
	if snowflake.dc, err = docker.NewDockerCli(nil, &snowflake.buf.out, &snowflake.buf.err, "unix", "/var/run/docker.sock"); err != nil {
		return nil, err
	}
	return
}
